<template>
  <div class="exercise-detail-container">
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <p>加载中...</p>
    </div>
    
    <!-- 错误信息 -->
    <div v-if="error" class="error-message">
      {{ error }}
    </div>
    
    <!-- 练习题不存在 -->
    <div v-if="!loading && !exercise" class="not-found">
      <h2>练习题不存在或已被删除</h2>
      <router-link to="/exercises" class="btn-back">返回练习题列表</router-link>
    </div>
    
    <!-- 练习题详情 -->
    <div v-if="exercise" class="exercise-content-wrapper">
      <div class="exercise-header">
        <div class="exercise-meta">
          <span :class="['exercise-type', exercise.type.toLowerCase()]">
            {{ getExerciseTypeText(exercise.type) }}
          </span>
          
          <span :class="['difficulty', exercise.difficulty.toLowerCase()]">
            {{ getDifficultyText(exercise.difficulty) }}
          </span>
          
          <span v-if="exercise.status" :class="['exercise-status', getStatusClass(exercise.status)]">
            {{ getStatusText(exercise.status) }}
          </span>
        </div>
        
        <div class="source-info" v-if="exercise.cardId">
          <p>
            <strong>知识点：</strong>
            <router-link :to="`/cards/${exercise.cardId}`">
              {{ exercise.cardTitle || '查看知识点' }}
            </router-link>
          </p>
        </div>
        
        <div class="document-info" v-if="exercise.documentId">
          <p>
            <strong>来源文档：</strong>
            <router-link :to="`/documents/${exercise.documentId}`">
              {{ exercise.documentTitle || '查看文档' }}
            </router-link>
          </p>
        </div>
      </div>
      
      <div class="exercise-body">
        <!-- 题目内容 -->
        <div class="question-section">
          <h2>题目</h2>
          <div class="question-content">
            {{ exercise.question }}
          </div>
        </div>
        
        <!-- 选择题 -->
        <div v-if="exercise.type === 'MULTIPLE_CHOICE'" class="multiple-choice-section">
          <h3>选项</h3>
          <div class="options-list">
            <div 
              v-for="(option, index) in exercise.options" 
              :key="index"
              class="option-item"
              :class="{
                'option-selected': userAnswer === option,
                'option-correct': showResult && option === exercise.answer,
                'option-incorrect': showResult && userAnswer === option && option !== exercise.answer
              }"
              @click="!showResult && selectOption(option)"
            >
              <div class="option-marker">{{ ['A', 'B', 'C', 'D', 'E', 'F'][index] }}</div>
              <div class="option-text">{{ option }}</div>
            </div>
          </div>
        </div>
        
        <!-- 填空题 -->
        <div v-if="exercise.type === 'FILL_BLANK'" class="fill-blank-section">
          <h3>答案</h3>
          <div class="fill-blank-input">
            <textarea 
              v-model="userAnswer" 
              placeholder="请输入答案..." 
              class="answer-textarea"
              :disabled="showResult"
              rows="4"
            ></textarea>
          </div>
        </div>
        
        <!-- 编程题 -->
        <div v-if="exercise.type === 'CODING'" class="coding-section">
          <h3>代码</h3>
          <div class="code-editor">
            <textarea 
              v-model="userAnswer" 
              placeholder="请输入代码..." 
              class="code-textarea"
              :disabled="showResult"
              rows="10"
            ></textarea>
          </div>
        </div>
        
        <!-- 提交按钮 -->
        <div class="submit-section" v-if="!showResult">
          <button 
            @click="submitAnswer" 
            class="btn-submit"
            :disabled="!userAnswer || submitting"
          >
            {{ submitting ? '提交中...' : '提交答案' }}
          </button>
        </div>
        
        <!-- 结果区域 -->
        <div v-if="showResult" class="result-section">
          <div :class="['result-box', isCorrect ? 'result-correct' : 'result-incorrect']">
            <div class="result-icon">{{ isCorrect ? '✓' : '✗' }}</div>
            <div class="result-message">
              <h3>{{ isCorrect ? '回答正确！' : '回答错误' }}</h3>
              <p v-if="!isCorrect">正确答案: {{ exercise.answer }}</p>
              <p v-if="exercise.explanation">{{ exercise.explanation }}</p>
            </div>
          </div>
          
          <div class="result-actions">
            <button @click="resetExercise" class="btn-retry">
              重新做题
            </button>
            
            <router-link :to="`/cards/${exercise.cardId}`" class="btn-view-card" v-if="exercise.cardId">
              查看知识点
            </router-link>
            
            <router-link to="/exercises" class="btn-next">
              下一题
            </router-link>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { exerciseApi } from '@/services/api';

const route = useRoute();
const router = useRouter();

// 状态变量
const loading = ref(false);
const error = ref('');
const exercise = ref(null);
const userAnswer = ref('');
const showResult = ref(false);
const isCorrect = ref(false);
const submitting = ref(false);

// 生命周期钩子
onMounted(async () => {
  const exerciseId = route.params.id;
  if (!exerciseId) return;
  
  await fetchExercise(exerciseId);
  
  // 如果已经做过这道题，显示之前的答案和结果
  if (exercise.value && (exercise.value.status === 'COMPLETED' || 
      exercise.value.status === 'CORRECT' || 
      exercise.value.status === 'INCORRECT')) {
    userAnswer.value = exercise.value.userAnswer || '';
    showResult.value = true;
    isCorrect.value = exercise.value.status === 'CORRECT';
  }
});

// 监听路由参数变化
watch(() => route.params.id, async (newId, oldId) => {
  if (newId && newId !== oldId) {
    // 重置状态
    userAnswer.value = '';
    showResult.value = false;
    isCorrect.value = false;
    
    await fetchExercise(newId);
    
    // 如果已经做过这道题，显示之前的答案和结果
    if (exercise.value && (exercise.value.status === 'COMPLETED' || 
        exercise.value.status === 'CORRECT' || 
        exercise.value.status === 'INCORRECT')) {
      userAnswer.value = exercise.value.userAnswer || '';
      showResult.value = true;
      isCorrect.value = exercise.value.status === 'CORRECT';
    }
  }
});

// 方法
const fetchExercise = async (exerciseId) => {
  loading.value = true;
  error.value = '';
  
  try {
    const response = await exerciseApi.getById(exerciseId);
    exercise.value = response.data;
  } catch (err) {
    error.value = '获取练习题失败';
    console.error('获取练习题失败:', err);
  } finally {
    loading.value = false;
  }
};

const selectOption = (option) => {
  userAnswer.value = option;
};

const submitAnswer = async () => {
  if (!exercise.value || !userAnswer.value) return;
  
  submitting.value = true;
  
  try {
    const response = await exerciseApi.submitAnswer(exercise.value._id, {
      answer: userAnswer.value
    });
    
    showResult.value = true;
    isCorrect.value = response.data.correct;
    
    // 更新练习题状态
    exercise.value = {
      ...exercise.value,
      status: response.data.correct ? 'CORRECT' : 'INCORRECT',
      userAnswer: userAnswer.value
    };
  } catch (err) {
    console.error('提交答案失败:', err);
  } finally {
    submitting.value = false;
  }
};

const resetExercise = () => {
  userAnswer.value = '';
  showResult.value = false;
};

// 辅助函数
const getExerciseTypeText = (type) => {
  const typeMap = {
    'MULTIPLE_CHOICE': '选择题',
    'FILL_BLANK': '填空题',
    'CODING': '编程题'
  };
  
  return typeMap[type] || type;
};

const getDifficultyText = (difficulty) => {
  const difficultyMap = {
    'EASY': '简单',
    'MEDIUM': '中等',
    'HARD': '困难'
  };
  
  return difficultyMap[difficulty] || difficulty;
};

const getStatusText = (status) => {
  const statusMap = {
    'INCOMPLETE': '未完成',
    'COMPLETED': '已完成',
    'CORRECT': '答对',
    'INCORRECT': '答错'
  };
  
  return statusMap[status] || status;
};

const getStatusClass = (status) => {
  const classMap = {
    'INCOMPLETE': 'status-incomplete',
    'COMPLETED': 'status-completed',
    'CORRECT': 'status-correct',
    'INCORRECT': 'status-incorrect'
  };
  
  return classMap[status] || '';
};
</script>

<style scoped>
.exercise-detail-container {
  max-width: 900px;
  margin: 0 auto;
  padding: 2rem;
}

.loading-container, .not-found {
  text-align: center;
  padding: 3rem;
}

.error-message {
  color: #ff3860;
  background-color: #feecf0;
  padding: 1rem;
  border-radius: 4px;
  margin-bottom: 1rem;
}

.btn-back {
  display: inline-block;
  padding: 0.75rem 1.5rem;
  background-color: #4CAF50;
  color: white;
  border-radius: 4px;
  text-decoration: none;
  margin-top: 1rem;
}

/* 练习题头部样式 */
.exercise-header {
  margin-bottom: 2rem;
  padding-bottom: 1.5rem;
  border-bottom: 1px solid #eee;
}

.exercise-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 1rem;
  margin-bottom: 1rem;
}

.exercise-type, .difficulty, .exercise-status {
  padding: 0.25rem 0.5rem;
  border-radius: 12px;
  font-size: 0.75rem;
  font-weight: 500;
}

.exercise-type.multiple_choice {
  background-color: #e3f2fd;
  color: #1976d2;
}

.exercise-type.fill_blank {
  background-color: #fff8e1;
  color: #ff8f00;
}

.exercise-type.coding {
  background-color: #e8f5e9;
  color: #2e7d32;
}

.difficulty.easy {
  background-color: #e8f5e9;
  color: #2e7d32;
}

.difficulty.medium {
  background-color: #fff8e1;
  color: #ff8f00;
}

.difficulty.hard {
  background-color: #ffebee;
  color: #c62828;
}

.status-incomplete {
  background-color: #f5f5f5;
  color: #757575;
}

.status-completed {
  background-color: #f3e5f5;
  color: #9C27B0;
}

.status-correct {
  background-color: #e8f5e9;
  color: #2e7d32;
}

.status-incorrect {
  background-color: #ffebee;
  color: #c62828;
}

.source-info, .document-info {
  margin-bottom: 0.5rem;
  color: #666;
}

.source-info a, .document-info a {
  color: #2196F3;
  text-decoration: none;
}

.source-info a:hover, .document-info a:hover {
  text-decoration: underline;
}

/* 练习题内容样式 */
.exercise-body {
  display: flex;
  flex-direction: column;
  gap: 2rem;
}

.question-section, 
.multiple-choice-section, 
.fill-blank-section, 
.coding-section,
.result-section {
  background-color: white;
  border-radius: 8px;
  padding: 1.5rem;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.question-section h2, 
.multiple-choice-section h3, 
.fill-blank-section h3, 
.coding-section h3 {
  margin-top: 0;
  margin-bottom: 1rem;
  color: #333;
}

.question-content {
  color: #333;
  line-height: 1.6;
  font-size: 1.1rem;
  white-space: pre-wrap;
}

/* 选择题样式 */
.options-list {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.option-item {
  display: flex;
  align-items: flex-start;
  padding: 1rem;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.2s ease;
}

.option-item:hover:not(.option-correct):not(.option-incorrect) {
  background-color: #f9f9f9;
}

.option-selected {
  border-color: #2196F3;
  background-color: #e3f2fd;
}

.option-correct {
  border-color: #4CAF50;
  background-color: #e8f5e9;
}

.option-incorrect {
  border-color: #F44336;
  background-color: #ffebee;
}

.option-marker {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 30px;
  height: 30px;
  border-radius: 50%;
  background-color: #f0f0f0;
  color: #333;
  font-weight: 500;
  margin-right: 1rem;
  flex-shrink: 0;
}

.option-selected .option-marker {
  background-color: #2196F3;
  color: white;
}

.option-correct .option-marker {
  background-color: #4CAF50;
  color: white;
}

.option-incorrect .option-marker {
  background-color: #F44336;
  color: white;
}

.option-text {
  flex: 1;
  line-height: 1.5;
}

/* 填空题样式 */
.answer-textarea, .code-textarea {
  width: 100%;
  padding: 1rem;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 1rem;
  resize: vertical;
}

.code-textarea {
  font-family: monospace;
  background-color: #f5f5f5;
}

.answer-textarea:focus, .code-textarea:focus {
  outline: none;
  border-color: #2196F3;
  box-shadow: 0 0 0 2px rgba(33, 150, 243, 0.2);
}

/* 提交区域样式 */
.submit-section {
  display: flex;
  justify-content: center;
  margin-top: 1rem;
}

.btn-submit {
  padding: 0.75rem 2rem;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 1rem;
  cursor: pointer;
}

.btn-submit:hover {
  background-color: #388E3C;
}

.btn-submit:disabled {
  background-color: #9e9e9e;
  cursor: not-allowed;
}

/* 结果区域样式 */
.result-box {
  display: flex;
  align-items: flex-start;
  padding: 1.5rem;
  border-radius: 8px;
  margin-bottom: 1.5rem;
}

.result-correct {
  background-color: #e8f5e9;
}

.result-incorrect {
  background-color: #ffebee;
}

.result-icon {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  font-size: 1.5rem;
  margin-right: 1.5rem;
  flex-shrink: 0;
}

.result-correct .result-icon {
  background-color: #4CAF50;
  color: white;
}

.result-incorrect .result-icon {
  background-color: #F44336;
  color: white;
}

.result-message {
  flex: 1;
}

.result-message h3 {
  margin-top: 0;
  margin-bottom: 0.5rem;
  font-size: 1.2rem;
}

.result-correct .result-message h3 {
  color: #2e7d32;
}

.result-incorrect .result-message h3 {
  color: #c62828;
}

.result-message p {
  margin: 0.5rem 0;
  color: #333;
}

.result-actions {
  display: flex;
  justify-content: center;
  gap: 1rem;
  margin-top: 1.5rem;
}

.btn-retry, .btn-view-card, .btn-next {
  padding: 0.75rem 1.5rem;
  border-radius: 4px;
  font-size: 0.9rem;
  cursor: pointer;
  text-align: center;
  text-decoration: none;
}

.btn-retry {
  background-color: transparent;
  color: #333;
  border: 1px solid #ddd;
}

.btn-retry:hover {
  background-color: #f0f0f0;
}

.btn-view-card {
  background-color: #2196F3;
  color: white;
  border: none;
}

.btn-view-card:hover {
  background-color: #1976D2;
}

.btn-next {
  background-color: #4CAF50;
  color: white;
  border: none;
}

.btn-next:hover {
  background-color: #388E3C;
}

/* 响应式布局 */
@media (max-width: 768px) {
  .exercise-meta {
    flex-direction: column;
    align-items: flex-start;
    gap: 0.5rem;
  }
  
  .result-box {
    flex-direction: column;
    align-items: center;
    text-align: center;
  }
  
  .result-icon {
    margin-right: 0;
    margin-bottom: 1rem;
  }
  
  .result-actions {
    flex-direction: column;
    gap: 0.75rem;
  }
  
  .btn-retry, .btn-view-card, .btn-next {
    width: 100%;
  }
}
</style> 